
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_nft/provider/LoginProvider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../api/API.dart';


class RegisterCode extends StatefulWidget {
  @override
  _RegisterCodeState createState() => _RegisterCodeState();
}

class _RegisterCodeState extends State<RegisterCode> {


  late String telephone;


  final TextEditingController _controller1 = TextEditingController();

  final TextEditingController _controller2 = TextEditingController();

  final TextEditingController _controller3 = TextEditingController();

  final TextEditingController _controller4 = TextEditingController();


  FocusNode cc1 = FocusNode();
  FocusNode cc2 = FocusNode();
  FocusNode cc3 = FocusNode();
  FocusNode cc4 = FocusNode();

  // This is the entered code

  // It will be displayed in a Text widget

  String? _otp;

  @override
  void initState() {
    //FocusScope.of(context).requestFocus(cc1);

    // TODO: implement initState
    super.initState();
    _controller1.addListener(() {

      if(_controller1.value.text.toString().length > 0){
        cc1.unfocus();

        FocusScope.of(context).requestFocus(cc2);

      }
    });

    _controller2.addListener(() {

      if(_controller2.value.text.toString().length > 0){
        cc2.unfocus();

        FocusScope.of(context).requestFocus(cc3);

      }
      // else{
      //   cc2.unfocus();
      //   FocusScope.of(context).requestFocus(cc1);
      // }
    });

    _controller3.addListener(() {

      if(_controller3.value.text.toString().length > 0){
        cc3.unfocus();

        FocusScope.of(context).requestFocus(cc4);

      }
      // else{
      //   cc3.unfocus();
      //   FocusScope.of(context).requestFocus(cc2);
      // }

    });

    _controller4.addListener(() {

      if(_controller4.value.text.toString().length > 0){

        //FocusScope.of(context).requestFocus(cc2);
        setState(() {
          _controller4.value.text.toString();
        });
      }
      // else{
      //   cc4.unfocus();
      //   FocusScope.of(context).requestFocus(cc3);
      // }

    });


  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller1.dispose();
    _controller2.dispose();
    _controller3.dispose();
    _controller4.dispose();
    cc1.dispose();
    cc2.dispose();
    cc3.dispose();
    cc4.dispose();
  }
  
  _getLogin(String phone,String code,BuildContext context)async{
    print("发送请求");
    var result = await new Dio().post(API.reqUrl+"/api/account/registory/"+phone+"/"+code,
    data: {
      "openId":context.read<LoginProvider>().getOpenId().toString(),
    }
    );
    if(result.data["flag"] == true){
      print("登录成功................");
      print(result.data.toString());
      SharedPreferences prefs = await SharedPreferences.getInstance();
      //存入缓存
      String phone = result.data["telePhone"];
      bool isLogin = result.data["flag"];

      print(phone.toString());
      //String token = result.data["token"];
      await prefs.setString("phone",phone.toString());
      await prefs.setBool("isLogin", isLogin);

      //String resultToken = (await prefs.setString("token",token)) as String;
      // print("存入缓存..的数据...");

       //print(resultToken);
      // //存入状态
      //context.read<LoginProvider>().setToken(token.toString());
      context.read<LoginProvider>().setUserName(phone.toString());
      context.read<LoginProvider>().setIsLogin(true);

      BrnToast.show(
        "登录成功..",
        context,
        // preIcon: Image.asset(
        //   "assets/image/icon_toast_success.png",
        //   width: 24,
        //   height: 24,
        // ),
        duration: BrnDuration.short,
      );


      //登录成功
      Navigator.of(context).pushNamed("tabbar");


    }
  }

  @override
  Widget build(BuildContext context) {
    Object? teacherMap = ModalRoute.of(context)!.settings.arguments;
    print("传来的参数"+teacherMap.toString());

    setState(() {
      telephone = teacherMap.toString();
    });
    return Padding(
      padding: EdgeInsets.all(20),
      child: Container(
        alignment: Alignment.bottomLeft,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        //color: Colors.lightGreen,
        child: Container(
          alignment: Alignment.bottomLeft,
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(
                height: 20,
              ),
              InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Container(
                    alignment: Alignment.bottomLeft,
                    width: MediaQuery.of(context).size.width,
                    height: 30,
                    child: Icon(
                      Icons.arrow_back_ios_rounded,
                      size: 25,
                      color: Colors.white,
                    )),
              ),
              SizedBox(
                height: 50,
              ),
              Container(
                margin: EdgeInsets.only(left: 15),
                alignment: Alignment.bottomLeft,
                width: MediaQuery.of(context).size.width,
                height: 100,
                child: Column(
                  children: [
                    Text(
                      "输入短信验证码",
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Padding(
                padding: EdgeInsets.only(left: 15),
                child: Container(
                    width: MediaQuery.of(context).size.width,
                    alignment: Alignment.bottomLeft,
                    child: Text(
                      "验证码已发送至您的手机号,请在下方输入6位数字验证码",
                      style: TextStyle(
                          fontSize: 10,
                          color: Color.fromRGBO(153, 155, 154, 1)),
                    )),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  //const Text('请输入验证码'),

                  const SizedBox(
                    height: 30,
                  ),

                  // Implement 4 input fields

                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 0, right: 0),
                        child: Container(
                          width: 30,
                          height: 30,
                          child: TextField(
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(1)
                            ],
                            autofocus: true,
                            focusNode: cc1,
                            textAlign: TextAlign.center,
                            controller: _controller1,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 0, right: 0),
                        child: Container(
                          width: 30,
                          height: 30,
                          child: TextField(
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(1)
                            ],
                            focusNode: cc2,
                            //autofocus: _c2,
                            textAlign: TextAlign.center,
                            controller: _controller2,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 0, right: 0),
                        child: Container(
                          width: 30,
                          height: 30,
                          child: TextField(
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(1)
                            ],
                            focusNode: cc3,
                            //autofocus: _c3,
                            textAlign: TextAlign.center,
                            controller: _controller3,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 0, right: 0),
                        child: Container(
                          width: 30,
                          height: 30,
                          child: TextField(
                            //限制长度
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(1)
                            ],
                            focusNode: cc4,
                            //focusNode: cc1,
                            textAlign: TextAlign.center,
                            controller: _controller4,
                          ),
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(
                    height: 30,
                  ),

                  InkWell(
                    onTap: (){
                      String codeList = _controller1.value.text.toString() + _controller2.value.text.toString() +  _controller3.value.text.toString()+ _controller4.value.text.toString();
                        if((codeList).length ==4){
                          //dio...
                          print("验证码手机号"+ codeList + telephone.toString());
                          _getLogin(telephone.toString(),codeList,context);
                          
                        }
                    },
                    child: Container(
                      alignment: Alignment.center,
                       width: 100,height: 40,
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(40),color: Colors.orange),
                        child: const Text('提交',style: TextStyle(fontSize: 18,color: Colors.white),)),
                  ),

                  const SizedBox(
                    height: 30,
                  ),

                ],
              ),

              // Container 手写一个........
            ],
          ),
        ),
      ),
    );
  }
}

class OtpInput extends StatelessWidget {
  final TextEditingController controller;

  final bool autoFocus;

  const OtpInput(this.controller, this.autoFocus, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 35,
      width: 35,
      child: TextField(
        autofocus: autoFocus,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        controller: controller,
        maxLength: 1,
        cursorColor: Theme.of(context).primaryColor,
        decoration: const InputDecoration(
            border: OutlineInputBorder(),
            counterText: '',
            hintStyle: TextStyle(color: Colors.white24, fontSize: 16.0)),
        onChanged: (value) {
          if (value.length == 1) {
            FocusScope.of(context).nextFocus();
          }
        },
      ),
    );
  }
}
